package cn.m19.lof.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.m19.lof.entity.SysAccount;
import cn.m19.lof.service.SysAccountService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LoginController {

    private final SysAccountService sysAccountService;

    @PostMapping("/login")
    public SaResult login(String username, String password) {
        SysAccount account = sysAccountService.queryChain()
            .eq(SysAccount::getUsername, username)
            .eq(SysAccount::getPassword, password)
            .one();
        if (account == null) {
            return SaResult.error("用户名或密码错误");
        }
        StpUtil.login(account.getId());
        return SaResult.data(StpUtil.getTokenInfo());
    }

    @PutMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }

    @GetMapping("/tokenInfo")
    public SaResult tokenInfo() {
        return SaResult.data(StpUtil.getTokenInfo());
    }

}
